package com.usdt.web.controller.cp.salesTools;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.usdt.common.core.domain.R;
import com.usdt.system.cp.utils.UserAndDeptUtils;
import com.usdt.system.domain.SysUserOnline;
import com.usdt.system.domain.req.RoomSaleCountdataExportReqVO;
import com.usdt.system.domain.resp.RoomBuildingNumberRespVO;
import com.usdt.system.domain.resp.RoomSaleChart2RespVo;
import com.usdt.system.domain.resp.RoomSalesChartRespVo;
import com.usdt.system.dto.cp.RoomSaleChartExcelDTO;
import com.usdt.system.service.cp.SalesChartService;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;

@RestController
@RequestMapping("/salesChart")
@Slf4j
@Tag(name = "销控图")
public class SalesChartController {

	@Autowired
	private SalesChartService salesChartService;
	
    @GetMapping("/buildingNumber")
    @Operation(summary ="楼号/楼层")
    public R<List<RoomBuildingNumberRespVO>> buildingNumber(
    		@Schema(description = "项目ids")@RequestParam(value = "deptIds", required = false)List<String> deptIds
    		) {
    	
    	return R.ok(salesChartService.buildingNumber(deptIds));
    }
    
    @GetMapping("/roomInfo")
    @Operation(summary ="销控图")
    public R<RoomSalesChartRespVo> getRoomInfo(
			@Schema(description = "楼栋")@RequestParam(value = "buildings", required = false)List<String> buildings,
			@Schema(description = "楼层")@RequestParam(value = "floors", required = false)List<String> floors,
			@Schema(description = "房间号")@RequestParam(value = "roomName", required = false)String roomName,
			@Schema(description = "房间类型（单人间/双人间/多人间）")@RequestParam(value = "numbers", required = false)List<String> numbers,
			@Schema(description = "会籍状态")@RequestParam(value = "vipTypes", required = false)List<String> vipTypes,
			@Schema(description = "房间朝向")@RequestParam(value = "faces", required = false)List<String> faces,
			@Schema(description = "入住状态（入住，闲置）")@RequestParam(value = "status", required = false)String status,
			@Schema(description = "客房类型（自理，短柱，护理）")@RequestParam(value = "roomType", required = false)String roomType,
			@Schema(description = "页码")@RequestParam(value = "pageNum", required = true,defaultValue="1") Integer pageNum,
			@Schema(description = "每页显示记录数")@RequestParam(value = "pageSize", required = true,defaultValue="10") Integer pageSize
    		) {
    	return R.ok(salesChartService.getRoomInfo(buildings,floors,roomName,numbers,vipTypes,faces,status,roomType,pageNum,pageSize));
    }
    
    @GetMapping("/roomInfo/count")
    @Operation(summary ="销控图-统计")
    public R<RoomSalesChartRespVo> getRoomInfoCount(
    		@Schema(description = "楼栋")@RequestParam(value = "buildings", required = false)List<String> buildings,
    		@Schema(description = "楼层")@RequestParam(value = "floors", required = false)List<String> floors,
    		@Schema(description = "房间号")@RequestParam(value = "roomName", required = false)String roomName,
    		@Schema(description = "房间类型（单人间/双人间/多人间）")@RequestParam(value = "numbers", required = false)List<String> numbers,
    		@Schema(description = "会籍状态")@RequestParam(value = "vipTypes", required = false)List<String> vipTypes,
    		@Schema(description = "房间朝向")@RequestParam(value = "faces", required = false)List<String> faces,
    		@Schema(description = "入住状态（入住，闲置）")@RequestParam(value = "status", required = false)String status,
    		@Schema(description = "客房类型（自理，短柱，护理）")@RequestParam(value = "roomType", required = false)String roomType
    		) {
    	return R.ok(salesChartService.getRoomInfoCount(buildings,floors,roomName,numbers,vipTypes,faces,status,roomType));
    }
    
    @GetMapping("/saleCount")
    @Operation(summary ="销售工具-客房统计")
    public R<RoomSalesChartRespVo> getSaleCount(
    		@Schema(description = "楼栋")@RequestParam(value = "buildings", required = false)List<String> buildings,
			@Schema(description = "楼层")@RequestParam(value = "floors", required = false)List<String> floors,
			@Schema(description = "客房类型（自理，短柱，护理）")@RequestParam(value = "roomType", required = false)String roomType,
    		@Schema(description = "deptIds")@RequestParam(value = "deptIds", required = false)List<String> deptIds
    		) {
    	
    	return R.ok(salesChartService.getSaleCount(buildings, floors, roomType, deptIds));
    }
    
	@GetMapping("/saleCount/data")
	@Operation(summary ="销售工具-客房统计-下钻")
	public R<IPage<RoomSaleChart2RespVo>> getSaleCountData(
			@Schema(description = "楼栋")@RequestParam(value = "buildings", required = false)List<String> buildings,
			@Schema(description = "楼层")@RequestParam(value = "floors", required = false)List<String> floors,
			@Schema(description = "客房类型（自理，短柱，护理）")@RequestParam(value = "roomType", required = false)String roomType,
			@Schema(description = "入住状态（入住，闲置）")@RequestParam(value = "status", required = false)String status,
			@Schema(description = "deptIds")@RequestParam(value = "deptIds", required = false)List<String> deptIds,
			@Schema(description = "页码")@RequestParam(value = "pageNum", required = true,defaultValue="1") Integer pageNum,
			@Schema(description = "每页显示记录数")@RequestParam(value = "pageSize", required = true,defaultValue="10") Integer pageSize,
			@Schema(description = "条件(json格式)")@RequestParam(value = "conditions", required = false) String conditions
			) {
		
		return R.ok(salesChartService.getSaleCountData(buildings, floors, roomType,status, deptIds,conditions,pageNum,pageSize));
	}
	
	@PostMapping("/saleCount/data/export")
	@Operation(summary ="销售工具-客房统计-下钻-导出")
	public void getSaleCountDataExport(
			HttpServletResponse response,
			@RequestBody @Valid RoomSaleCountdataExportReqVO vo
			) throws IOException {
		
		List<RoomSaleChartExcelDTO> list = salesChartService.getSaleCountDataExport(vo.getBuildings(), 
				vo.getFloors(), vo.getRoomType(),
				vo.getStatus(), 
				vo.getDeptIds(),
				vo.getConditions());
		exportExcel(response,list,RoomSaleChartExcelDTO.class,"客房状态数据","客房状态数据");
	}
	
    public void exportExcel(HttpServletResponse response, List dataList, Class clazz
    		,String excelName,String sheetName) throws IOException {
        // 1. 设置响应头（关键：避免中文乱码、指定文件类型）
    	response.addHeader("Pargam", "no-cache");
    	response.addHeader("Cache-Control", "no-cache");
    	response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        //response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); // Excel 2007+格式
    	//response.setContentType("application/octet-stream;charset=UTF-8"); // Excel 2007+格式
        response.setCharacterEncoding("utf-8");
        // 文件名编码：使用URLEncoder避免中文乱码，替换“+”为“%20”（浏览器兼容）
        String fileName = URLEncoder.encode(excelName, "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + fileName + ".xlsx");

        // 2. 使用EasyExcel写入数据（try-with-resources自动关闭ExcelWriter）
        try (var excelWriter = EasyExcel.write(response.getOutputStream(), clazz).build()) {
            // 3. 构建Sheet（指定工作表名称，如“活动信息”）
            var sheet = EasyExcel.writerSheet(sheetName).build();
            // 4. 写入数据（将实体类列表映射为Excel行）
            excelWriter.write(dataList, sheet);
        }
    }
}
